package com.dxy.dxyuser.service.impl;

import com.dxy.dxycommon.VO.AddressVO;
import com.dxy.dxyuser.DO.UserAddress;
import com.dxy.dxyuser.repository.UserAddressRepository;
import com.dxy.dxyuser.service.AddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * junfeng 2018/10/31 地址管理service
 */
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private UserAddressRepository userAddressRepository;


    @Override
    public UserAddress addAddress(AddressVO addressVO) {
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(addressVO, userAddress);
        return userAddressRepository.save(userAddress);
    }

    @Override
    public void deleteAddress(Integer id) {
        userAddressRepository.deleteById(id);
    }

    @Override
    public List<AddressVO> listAddress(String userId) {
        List<UserAddress> addresses = userAddressRepository.findByUserId(userId);
        List<AddressVO> addressVOS = new ArrayList<>();
        for (UserAddress address : addresses) {
            AddressVO addressVO = new AddressVO();
            BeanUtils.copyProperties(address, addressVO);
            addressVOS.add(addressVO);
        }
        return addressVOS;
    }

    @Override
    public AddressVO selectAddress(Integer id) {
        Optional<UserAddress> userAddress = userAddressRepository.findById(id);
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(userAddress.get(),addressVO);
        return addressVO;
    }


}
